package leetcode_400;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;

import helpclass.Interval;

/**
 *@author 周杨
 *DataStreamAsDisjointIntervals_352  在一个区间集合内增加数 改变区间集合 和返回集合
 *describe:简单题 AC 98%
 *2018年7月8日 上午11:50:56
 */
public class DataStreamAsDisjointIntervals_352 {
	private TreeSet<Interval> intervalSet; 
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}
	/** Initialize your data structure here. */
    public DataStreamAsDisjointIntervals_352() {
    	intervalSet = new TreeSet<Interval>(new Comparator<Interval>() {
            public int compare(Interval a, Interval b) {
                return a.start - b.start;
            }
        });
    }
    
    public void addNum(int val) {
    	 Interval valInterval = new Interval(val, val);
         Interval floor = intervalSet.floor(valInterval);
         if (floor != null) {
             if (floor.end >= val) {
                 return;
             } else if (floor.end + 1 == val) {
                 valInterval.start = floor.start;
                 intervalSet.remove(floor);
             }
         }
         Interval higher = intervalSet.higher(valInterval);
         if (higher != null && higher.start == val + 1) {
             valInterval.end = higher.end;
             intervalSet.remove(higher);
         }
         intervalSet.add(valInterval);
    }
    
    public List<Interval> getIntervals() {
    	return Arrays.asList(intervalSet.toArray(new Interval[0]));
    }
}
